package com.gexiaobao.pigeon.ui.fragment.mine.pigeon

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.EditorInfo
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.TransInformation
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentAutotrophicBinding
import com.gexiaobao.pigeon.ui.adapter.MyPigeonAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.MyPigeonViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 16:39
 * @Describe    : 我的赛鸽-自养
 */
class FragmentAutotrophic : BaseFragment<MyPigeonViewModel, FragmentAutotrophicBinding>() {

    private lateinit var dialog: RxDialogDefault
    private val mAdapter: MyPigeonAdapter by lazy { MyPigeonAdapter(arrayListOf()) }

    //界面状态管理者
    private lateinit var loadsir: LoadService<Any>

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        mViewModel.pigeonNum.set(getString(R.string.pigeon_number_zero))
        mViewModel.pigeonType.set("1")
        mViewModel.autoPigeon.set(true)
        mViewModel.fosterPigeon.set(false)

        mDatabind.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchPigeon()

                else -> {}
            }
            false
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 1f)))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getPigeonList(false, "1", mViewModel.searchName.get())
            }
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getPigeonList(true, "1", mViewModel.searchName.get())
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getPigeonList(true, "1", mViewModel.searchName.get())
        }

        mAdapter.run {
            setOnItemClickListener { _, _, position ->
                nav().navigateAction(R.id.action_mien_pigeon_to_detail_pigeon, Bundle().apply {
                    putString("pigeonId", mAdapter.data[position].pigeonId.toString())
                    putString("type", "auto")
                    putBoolean("intentType", true)
                    putSerializable("pigeonData", mAdapter.data[position])
                })
            }
        }

        mAdapter.addChildClickViewIds(R.id.tv_item_pigeon_delete)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_pigeon_delete -> {
                    deletePigeon(position)
                }
            }
        }
    }

    override fun initData() {
        super.initData()

        mDatabind.etSearch.transformationMethod = TransInformation()//小写自动转大写
        eventViewModel.toRefreshList.observeInFragment(this) {
            if (it) {
                loadsir.showLoading()
                mViewModel.getPigeonList(true, "1", mViewModel.searchName.get())
            }
        }

        mDatabind.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                if (s?.isEmpty() == true) {
                    mDatabind.tvDeleteAllPigeon.isVisible = true
                    loadsir.showLoading()
                    mViewModel.getPigeonList(true, "1", mViewModel.searchName.get())
                }
            }
        })
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvSearch, mDatabind.tvDeleteAllPigeon, mDatabind.tvAutoAddPigeon) {
            when (it) {
                mDatabind.tvAutoAddPigeon -> {
                    nav().navigateAction(R.id.action_mien_pigeon_to_add_pigeon, Bundle().apply {
                        putString("title", getString(R.string.add_pigeon))
                        putInt("type", 1)
                    })
                }

                mDatabind.tvSearch -> {
                    mDatabind.tvDeleteAllPigeon.isVisible = false
                    searchPigeon()
                }

                mDatabind.tvDeleteAllPigeon -> {
                    deleteAllPigeon()
                }
            }
        }
    }

    private fun deleteAllPigeon() {
        dialog = RxDialogDefault(context)
        dialog.setTitle(getString(R.string.is_delete_all_pigeons))
        dialog.setSureListener {
            showConfirmDialog()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showConfirmDialog() {
        val dialogCon = RxDialogDefault(context)
        dialogCon.setTitle(getString(R.string.is_sure_delete_all_pigeons))
        dialogCon.setLeftBtnContent(getString(R.string.sure))
        dialogCon.setRightBtnContent(getString(R.string.cancel))
        dialogCon.setCancelListener {
            dialogCon.dismiss()
            mViewModel.deletePigeonList()
        }
        dialogCon.setSureListener {
            dialogCon.dismiss()
        }
        dialogCon.setFullScreenWidth()
        dialogCon.show()
    }

    private fun searchPigeon() {
        hideSoftKeyboard(activity)
        when {
            mViewModel.searchName.get().isEmpty() -> showMessage(getString(R.string.please_enter_search_ring))
            else -> {
                loadsir.showLoading()
                mViewModel.getPigeonList(true, "1", mViewModel.searchName.get())
            }
        }
    }

    private fun deletePigeon(position: Int) {
        dialog = RxDialogDefault(context)
        dialog.setTitle(getString(R.string.is_delete_this_pigeon))
        dialog.setSureListener {
            dialog.dismiss()
            mViewModel.deletePigeon(mAdapter.data[position].pigeonId.toString())
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun onResume() {
        super.onResume()
        loadsir.showLoading()
        mViewModel.getPigeonList(true, "1", mViewModel.searchName.get())
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.pigeonData.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                mViewModel.pigeonNum.set(getString(R.string.pigeon_numbers) + ":" + it.total + getString(R.string.yu))
                loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
            } else {
                RxToast.showToast(it.errMessage)
            }
        }

        mViewModel.deletePigeon.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                dialog.dismiss()
                loadsir.showLoading()
                mViewModel.getPigeonList(true, "1", mViewModel.searchName.get())
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        mViewModel.deleteAllPigeon.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                dialog.dismiss()
                loadsir.showLoading()
                mViewModel.getPigeonList(true, "1", mViewModel.searchName.get())
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }
}